package lib.gui;

import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import lib.Base.Profile;
import lib.Common.Path;
import lib.FileSystem.Check;
import lib.FileSystem.Make;
import lib.XML.XMLWriter;
import lib.Common.UserId;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;

import org.swixml.SwingEngine;
import org.swixml.XDialog;

public class GuiRegistration {
	/**
	 * Class which represents a registration form
	 */
	private SwingEngine engine;
	private XDialog container;
	private JTextField input_username;
	private JPasswordField input_password;
	private JPasswordField input_password_retype;
	
	public Action handleClick = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
        	
        	if(e.getActionCommand().equals("Register")){
        		
        		String username = input_username.getText();
        		String password = String.valueOf(input_password.getPassword());
        		String password2 = String.valueOf(input_password_retype.getPassword());
        		
        		if(username.length() < 3){
        			JOptionPane.showMessageDialog(null, "Username must contain 3 or more characters", "Username Error", JOptionPane.ERROR_MESSAGE);
        		}else{
        			if(!(username.matches("^[a-zA-Z0-9_]*$"))){
            			JOptionPane.showMessageDialog(null, "Username must consist only of alphanumeric characters", "Username Error", JOptionPane.ERROR_MESSAGE);
            		}else{
            			if(password.length() < 5){
            				JOptionPane.showMessageDialog(null, "Password must contain 5 or more characters", "Password Error", JOptionPane.ERROR_MESSAGE);
            			}else{
            				if(password.equals(password2)){
                    			//All valid, go ahead
            					String userId = UserId.createId();
            					Make.CREATE_DIR(Path.RES_DIR);
            					if(Check.EXISTS(Path.RES_DIR)) {
            						try {
            							ZipFile zipFile = new ZipFile(Path.PROG_DIR + "default_layout.zip");
            							zipFile.extractAll(Path.RES_DIR);
            						} catch (ZipException z) {
            							JOptionPane.showMessageDialog(null, "default_layout.zip was not found", "Layout Error", JOptionPane.ERROR_MESSAGE);
            							return;
            						}
            					}
            					Make.CREATE_DIR(Path.XML_PATH_CONVERSATION);
            					Make.CREATE_DIR(Path.XML_PATH_PROFILES);
            					Profile tmpProfile = new Profile();
            					tmpProfile.setUserId(userId);
            					tmpProfile.setUsername(username);
            					tmpProfile.setLastChange(UserId.getTimestamp());
            					try {
            						new XMLWriter().WriteProfile(tmpProfile, Path.XML_PATH_PROFILES+userId+".xml");
								} catch (Exception e2) {}
            					
            					container.dispose();
            					engine = null;
            					new GuiMain(username, userId, password);
            					
                    		}else{
                    			JOptionPane.showMessageDialog(null, "Password match failed", "Password Error", JOptionPane.ERROR_MESSAGE);
                    		}
            			}
            		}
        		}
        	}else if(e.getActionCommand().equals("Cancel")){
        		container.dispose();
        		container = null;
        		engine = null;
        		new GuiLogin();
        	}
        }
    };

	public GuiRegistration() {
		try {
			engine = new SwingEngine(this);
			container = (XDialog)engine.render(new File(Path.SYS_XML + "gui-registration.xml"));
			container.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}